const fs = require('fs');
const URL = require('url');
const path = require('path');
const http = require('http');

const dir = 'D:/soft';
const url = 'http://upload.liuzy88.com/';

(async()=>{
    const args = process.argv.splice(2);
    const f = args[0];
    if (f) {
        const file = path.join(dir, f);
        if (fs.existsSync(file)) {
            console.log(`文件${file}已存在`);
        } else {
            await download(url + encodeURI(f), file);
        }
    }
})().catch(err => console.log(err))


async function download(url, dst, headers) {
    console.log(`download start: ${url} => ${dst}`);
    const options = URL.parse(url);
    options.method = 'GET';
    options.headers = headers || {
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,ja;q=0.7,zh-TW;q=0.6',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
    };
    return new Promise(function(resolve, reject) {
        const start = Date.now();
        const ws = fs.createWriteStream(dst);
        const agent = (options.protocol === 'https:' ? https : http);
        const req = agent.request(options, (res) => {
            res.setTimeout(5000);
            res.pipe(ws);
            res.on('end', () => {
                console.log(`download end: ${dst} cost ${Date.now() - start}ms`);
                ws.close();
                resolve(dst);
            });
        });
        req.setTimeout(5000);
        req.on('error', (err) => {
            console.log(`download error: ${err.message}`);
            reject(err);
        });
        req.end();
    });
}